if(history.scrollRestoration){
    history.scrollRestoration = 'manual';
}
// 头部
$(function(){
    // 点击更多 弹出侧边栏
    $('header .showMore').on('click',function(){
        $('aside').show();
        $('aside .main').stop().animate({
            left:'0%'
        },200);
        $('aside .mask').stop().animate({
            backgroundColor:'rgba(0, 0, 0, 0.5)'
        },200);
    })
    // 点击遮罩  隐藏侧边栏
    $('aside .mask').on('click',function(){
        $('aside .main').stop().animate({
            left:'-80%'
        },200);
        $('aside .mask').stop().animate({
            backgroundColor:'rgba(0, 0, 0, 0)'
        },200);
        setTimeout(function(){$('aside').hide();},400);
    })
    // 点击关闭按钮  隐藏侧边栏
    $('aside .close').on('click',function(){
        $('aside .main').stop().animate({
            left:'-80%'
        },200);
        $('aside .mask').stop().animate({
            backgroundColor:'rgba(0, 0, 0, 0)'
        },200);
        setTimeout(function(){$('aside').hide();},400);
    })
})

// 检查用户是否有登陆
$(function(){
    $.ajax({
        type:'post',
        async:false,
        url:'/postUserSession',
        success:function(res){
            console.log('login res',res);
            var user = res.msg;
            if(res.status){
                console.log($('footer .container a:last-child').find('span.iconfont'))
                $('footer .container a:last-child').find('span.iconfont').remove();
                $('footer .container a:last-child').prepend($(`<div class="avatar"><img src="${user.avatar}" alt=""></div>`))
                $('aside .avatar img').attr('src',user.avatar);
                $('aside .username').html(user.nickname);
            }
            else{
                // 头像
                $('aside .mid .user').on('click',function(){
                    window.location.href = 'http://localhost:3000/login/login.html';
                })
                // 我的收藏+我的关注
                $('aside .mid .userFuncArea .top .item:lt(1)').on('click',function(){
                    window.location.href = 'http://localhost:3000/login/login.html';
                })
                // 底部
                $('aside .bd').on('click',function(){
                    window.location.href = 'http://localhost:3000/login/login.html';
                })
            }

            // 底部 购物车按钮
            $('footer .go_to_cart_page').on('click',function(){
                if(res.status){
                    window.location.href = `http://localhost:3000/app-shoppingCart.html`;
                }
                else{
                    window.location.href = 'http://localhost:3000/login/login.html';
                }
            })

            // 侧边购物车按钮
            $('aside .topFuncArea .item').eq(1).on('click',function(){
                if(res.status){
                    window.location.href = `http://localhost:3000/app-shoppingCart.html`;
                }
                else{
                    window.location.href = 'http://localhost:3000/login/login.html';
                }
            })
            
            // 退出登录按钮
            $('aside .logOut').on('click',function(){
                if(res.status){
                    $.ajax({
                        type:'post',
                        async:false,
                        url:'/logout',
                        success:function(res){
                            console.log('res',res);
                            if(res.status){
                                window.location.reload();
                            }
                        },
                        error:function(err){
                            console.log('err',err);
                        }
                    })
                }
                else{
                    $('aside .close').trigger('click');
                }
            })
        },
        error:function(err){
            console.log('err',err);
        }
    })
})


// 底部
$(function(){
    $('footer').on('click',function(e){
        var index = e.target.dataset.index;

        if(index){
            console.log($('footer .item').eq(index-1));
            $('footer .item').eq(index-1).addClass('current').siblings().removeClass('current');
        }
    })
})


// 懒加载
lazyLoadInit({
    coverColor:"white",
    coverDiv:"",
    offsetBottom:0,
    offsetTopm:0,
    showTime:200,
    onLoadBackEnd:function(i,e){
        // console.log("onLoadBackEnd:"+i);
    }
    ,onLoadBackStart:function(i,e){
        // console.log("onLoadBackStart:"+i);
    }
});



// 函数

// 点赞
function thumbsUpFunc(){
    $('.thumbsUp span.iconfont').on('click',function(e){
        if($(this).parent().hasClass('yes')){
            $(this).parent().removeClass('yes');
            $(this).parent().find('span.num').html($(this).parent().find('span.num').html() - 1);
        }
        else{
            $(this).parent().find('span.num').html(parseInt($(this).parent().find('span.num').html()) + 1);
            $(this).parent().addClass('yes');
        }
    })
}

// 文本溢出处理
// 参数1 元素id  
// 参数2 要限制的行数 
// 参数3 文本内容 
// 参数4 省略号文字的样式类名 
// 参数5 省略号文字
function moreLine(obj,rows,text,className,str){
    var obj = obj;
    var computedStyle = document.defaultView.getComputedStyle(obj,null);
    var lineHeight = computedStyle.lineHeight;
    var top = (rows+1)*parseInt(lineHeight);
    var tempStr = text;
    obj.innerHTML = tempStr;
    var len = tempStr.length;
    var i = 0;
    if(obj.offsetHeight>top){
        var temp = "";
        obj.innerHTML = temp;
        while(obj.offsetHeight<=top){
            temp = tempStr.substring(0,i+1);
            i++;
            obj.innerHTML = temp;
        }
        tempStr = temp.substring(0,temp.length-1);
        len = tempStr.length;
        obj.innerHTML = tempStr.substring(0,len-3)+`<span class="${className}">...${str}</span>`;
        obj.height = top+"px";


        obj.addEventListener('click',function(){
            console.log('click');
            obj.innerHTML = text;
        })
    }
}


// 初始化滑块 位置 和 添加点击事件
// 参数1：滑块的左/右边距值
function afterSlideFunc(marginBetween){
    $('.afterSlider').width($('.module_switch .current').width()-4);    //设置宽度
    $('.afterSlider').css('left',$('.module_switch .current').get(0).offsetLeft);      // 初始位置
    $('.afterSlider').show();

    // 点击时 修改文字样式 + 滑块移动
    $('.module_switch').on('click',function(e){
        var index = e.target.dataset.index;
        console.log(index);
        if(index){
            var slider_left = e.target.offsetLeft;
            
            $(e.target).addClass('current').siblings().removeClass('current');  //修改文字样式
            $('.afterSlider').width($(e.target).width()-marginBetween*2);      //设置宽度
            $('.afterSlider').css('left',slider_left);                  // 初始位置
        }
    })
}


// 获取图片色rgb颜色值
// 参数1：img图片对象 Object
// 参数2：canvas对象  Object
function getImageColor(img,canvas) {
    // var canvas = document.getElementById("myCanvas");  //canvas元素
    canvas.width = img.width;
    canvas.height = img.height;

    var context = canvas.getContext("2d");

    context.drawImage(img, 0, 0, canvas.width, canvas.height);

    // 获取像素数据
    var imgData = context.getImageData(0, 0, canvas.width, canvas.height);

    var r = 0, g = 0, b = 0, a = 0;
    // 取所有像素的平均值
    for (var row = 0; row < img.height; row++) {
        for (var col = 0; col < img.width; col++) {
            r += imgData.data[((img.width * row) + col) * 4];
            g += imgData.data[((img.width * row) + col) * 4 + 1];
            b += imgData.data[((img.width * row) + col) * 4 + 2];
        }
    }

    // 求取平均值
    r /= (canvas.width * canvas.height);
    g /= (canvas.width * canvas.height);
    b /= (canvas.width * canvas.height);

    // 将最终的值取整
    r = Math.round(r);
    g = Math.round(g);
    b = Math.round(b);

    let rgba = {r:r,g:g,b:b};
    return rgba;
}


// 星星 和 豆瓣评分
// 参数1：豆瓣评分
function ratingStarCalculate(rate){
    // 星级 
    var ratingClass = '';   // 自定义属性 data-rating
    switch(rate >= 0){
        case rate>=9.5:{ratingClass = 5.0;}break;
        case rate>=8.5 && rate<9.5:{ratingClass = 4.5;}break;
        case rate>=7.5 && rate<8.5:{ratingClass = 4.0;}break;
        case rate>=6.5 && rate<7.5:{ratingClass = 3.5;}break;
        case rate>=5.5 && rate<6.5:{ratingClass = 3.0;}break;
        case rate>=4.5 && rate<5.5:{ratingClass = 2.5;}break;
        case rate>=3.5 && rate<4.5:{ratingClass = 2.0;}break;
        case rate>=2.5 && rate<3.5:{ratingClass = 1.5;}break;
        case rate>=1.5 && rate<2.5:{ratingClass = 1.0;}break;
        case rate>=0.5 && rate<1.5:{ratingClass = 0.5;}break;
        case rate>=0:{ratingClass = 0.0;}break;
        default:break;
    }
    
    var spanRatingStarBox = `<span class="rating_stars small flexBox" data-rating="${ratingClass}">`;    // 星星容器
    var spanRatingStar = '';    // 星星盒子
    var hasRating = '';         // 暂无评分 时 添加类名为no_rating

    // 黄色 半个 灰色 星星 的个数
    var full = 0, half = 0, gray = 0;
    full = Math.floor(ratingClass);
    half = Math.ceil(ratingClass - Math.floor(ratingClass));
    gray = Math.floor(5 - ratingClass);
    // console.log(ratingClass,full,half,gray);

    for(var i = 0; i<full; i++){
        spanRatingStar += '<span class="rating_stars_item rating_stars_item_full small"></span>';
    }
    if(half == 1) spanRatingStar += '<span class="rating_stars_item rating_stars_item_half small"></span>';
    if(gray != 5){
        for(var i = 0; i<gray; i++){
            spanRatingStar += '<span class="rating_stars_item rating_stars_item_gray small"></span>';
        }
        spanRatingStarBox += spanRatingStar;
        spanRatingStarBox += '</span>'
    }
    else{
        spanRatingStarBox = '';
        hasRating = 'no_rating';
    }

    return [spanRatingStarBox,hasRating];
}
